package com.haiwen.service.impl;

import com.haiwen.mapper.usersMapper;
import com.haiwen.pojo.users;
import com.haiwen.service.registerLoginService;
import com.haiwen.utils.DateStringMutual;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class registerLoginServiceImpl implements registerLoginService {
    @Autowired
    usersMapper mapper;

    @Override
    public int regist(users users) {
        users users1 = mapper.isregist(users.getUname());
        if (users1 == null) {
            Date date = new Date();
            String dateTime = DateStringMutual.DateToStringUtil(date);
            String Md5Upass = DigestUtils.md5DigestAsHex(users.getUpass().getBytes());
            users.setUpass(Md5Upass);
            users.setLogintime(dateTime);
            return mapper.regist(users);
        }
        return 0;
    }

    @Override
    public int Login(String uname, String isroot, String unpass) {
        /*0为管理员*/
        if (mapper.SelectAccount(uname, isroot) != null) {
            //更新登录时间
            users login = mapper.login(uname);
            Date date = new Date();
            String loginTimeString = login.getLogintime();
            Date  loginTime = DateStringMutual.StringToDateUtil(loginTimeString);
            if (loginTime!=null){
                //定义次数
                int nums = login.getLognums();
                //设置登录时间
                String md5unpass = DigestUtils.md5DigestAsHex(unpass.getBytes());
                if (nums >= 3) {
                    //错误大于三次，账号锁定2分钟
                    Date addTo2MinuteLoginTime = new Date(date.getTime() + 120000);
                    String dateTimeTo2Minute = DateStringMutual.DateToStringUtil(addTo2MinuteLoginTime);
                    mapper.updateRegist(dateTimeTo2Minute, uname);
                    mapper.updateErrnums(0,uname);
                    //账号锁定
                    return 3;
                }else if(date.getTime()<loginTime.getTime()){
                    return 3;
                }else if (login.getUname().equals(uname) && login.getUpass().equals(md5unpass)) {
                    mapper.updateErrnums(0, uname);
                    //账号和密码都正确
                    return 2;
                } else if (!login.getUpass().equals(md5unpass)) {
                    mapper.updateErrnums(nums + 1, uname);
                }
            }
            //登录失败次数
            return 1;
        } else {
            //登录失败 账号不存在
            return 0;
        }
    }
}
